package com.tencent.wxcloudrun.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.tencent.wxcloudrun.service.IEmailService;
import com.tencent.wxcloudrun.controller.utils.ResultResponse;
import com.tencent.wxcloudrun.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private SnowFlake snowFlake;

    @Autowired
    private IEmailService emailService;

    @Autowired
    private TemplateEngine templateEngine;

    // 会话登录接口
    @GetMapping("/login")
    public ResultResponse doLogin(@RequestParam String name, @RequestParam String pwd) {
        // 第一步：比对前端提交的账号名称、密码
        if ("zhang".equals(name) && "123456".equals(pwd)) {
            // 第二步：根据账号id，进行登录
            StpUtil.login(10001);
            Map<String, String> map = new HashMap<>();
            map.put("token", StpUtil.getTokenInfo().tokenValue);
            map.put("id", String.valueOf(snowFlake.getID()));
            return ResultResponse.ok(map, "登录成功");
        }
        return ResultResponse.error("登录失败");
    }

    @GetMapping("/email")
    public void sendEmail() {
        Context context = new Context();
        context.setVariable("verifyCode", "NH7K".toCharArray());
        String content = templateEngine.process("VerifyCode.html", context);
        emailService.sendHtml("846163332@qq.com", "846163332@qq.com", "『 meet-food应用提醒 』", content);
    }
}
